package com.css.fxfzdzzh.modules.taskManage.repository.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzdzzh.constants.FxfzConstants;
import com.css.fxfzdzzh.constants.YNEnum;
import com.css.fxfzdzzh.enums.DisasterTypeEnum;
import com.css.fxfzdzzh.enums.ResultEnum;
import com.css.fxfzdzzh.modules.evaluate.entity.TaskVersion;
import com.css.fxfzdzzh.modules.taskManage.entity.TaskDistrictArea;
import com.css.fxfzdzzh.modules.taskManage.entity.TaskEntity;
import com.css.fxfzdzzh.modules.taskManage.repository.TaskRepository;
import com.css.fxfzdzzh.modules.taskManage.vo.TaskQueryVO;
import com.css.fxfzdzzh.modules.taskManage.vo.TaskUpdateVO;
import com.css.fxfzdzzh.modules.tifData.service.ElevationMapService;
import com.css.fxfzdzzh.util.CreateGson;
import com.css.fxfzdzzh.util.PlatformObjectUtils;
import com.css.fxfzdzzh.web.PlatformSessionContext;
import com.css.fxfzdzzh.zcpt.sys.entity.SUser;
import com.css.fxfzdzzh.zcpt.sys.service.SUserService;
import com.css.fxfzdzzh.zcpt.sys.service.SysAreaService;
import com.css.fxfzdzzh.zcpt.sys.service.SysRoleService;
import jdk.nashorn.internal.runtime.FindProperty;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Dbj
 * @date 2023年02月13日  14:22
 */
@Repository
public class TaskRepositoryImpl implements TaskRepository {

    @Resource
    JdbcTemplate jdbcTemplate;
    @Resource
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Resource
    SUserService sUserService;

    @Resource
    SysRoleService sysRoleService;

    @Resource
    SysAreaService sysAreaService;

    @Resource
    ElevationMapService elevationMapService;

    @Override
    public void saveTask(TaskEntity taskEntity) {
        //处理空间数据，判断存在自相交则获取修复后的空间数据，否则返回原空间数据wkt
        String geomText = elevationMapService.getGeomValidWkt(taskEntity.getTaskRegion());
        taskEntity.setTaskRegion(geomText);

        String sql = "insert into dzzh_task (dt_id,task_num,task_name,task_region,task_district,task_status,create_user,create_time," +
                "del_flag,disaster_type,geom,create_user_name) values " +
                "(:dtId,:taskNum,:taskName,:taskRegion,:taskDistrict,:taskStatus,:createUser,:createTime,:delFlag,:disasterType,ST_GeometryFromText(:taskRegion,4490),:createUserName)";
        BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(taskEntity);
        namedParameterJdbcTemplate.update(sql, source);
    }

    @Override
    public void saveDistrictArea(TaskDistrictArea entity) {
        String sql = "insert into task_district_area (tda_id,tda_name,tda_area,dt_id) values " +
                "(:tdaId,:tdaName,:tdaArea,:dtId)";
        BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(entity);
        namedParameterJdbcTemplate.update(sql, source);
    }

    @Override
    public Map<String, Object> findTask(TaskQueryVO taskVo, int curPage, int pageSize) {
        Long start = System.currentTimeMillis();
        StringBuilder sql = new StringBuilder("select dt_id, task_num, task_name, task_region, task_district, task_status, create_user, create_time, update_user, update_time, del_flag, disaster_type, report_id, create_user_name from dzzh_task task where 1=1 ");
        StringBuilder whereSql = new StringBuilder("  and task.del_flag = '"+ YNEnum.N.toString() +"'");
        StringBuilder orderSql = new StringBuilder(" order by task.create_time desc");
        StringBuilder countSql = new StringBuilder(" select count(*) from dzzh_task task where 1=1");
        int firstIndex = (curPage - 1) * pageSize;
        int lastIndex = pageSize;

        StringBuilder str = new StringBuilder("");
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String role = sysRoleService.getRoleByUserId(userId);
        List<Map> roleMaps = JSONObject.parseArray(role, Map.class);
        for (Map roleMap : roleMaps) {
            str.append(roleMap.get("roleCode") + ",");
        }
        String roles = str.toString();
        /*if (!roles.contains(FxfzConstants.DZZH_COUN_GL_ROLE) && !roles.contains(FxfzConstants.DZZH_PRI_GL_ROLE)) {
            whereSql.append(" and create_user = '" + taskVo.getCreateUser() + "'");
        } else if (roles.contains(FxfzConstants.DZZH_PRI_GL_ROLE)) {
            String areaNameByAreaId = sysAreaService.getAreaNameByAreaId(sUser.getProvinceId());
            if (!PlatformObjectUtils.isEmpty(areaNameByAreaId)) {
                whereSql.append(" and task_district like '%" + areaNameByAreaId + "%'");
            }
        }*/
        whereSql.append(" and task.create_user = '" + taskVo.getCreateUser() + "'");
        StringBuilder limitSql = new StringBuilder(" limit " + lastIndex + " offset " + firstIndex);
        if (!PlatformObjectUtils.isEmpty(taskVo.getTaskNum())) {
            whereSql.append(" and task.task_num like '%" + taskVo.getTaskNum() + "%'");
        }
        if (!PlatformObjectUtils.isEmpty(taskVo.getTaskName())) {
            whereSql.append(" and task.task_name like '%" + taskVo.getTaskName() + "%'");
        }
        if (!PlatformObjectUtils.isEmpty(taskVo.getTaskStatus())) {
            whereSql.append(" and task.task_status = '" + taskVo.getTaskStatus() + "'");
        }
//        if (!PlatformObjectUtils.isEmpty(taskVo.getProvince()) || !PlatformObjectUtils.isEmpty(taskVo.getCity()) || !PlatformObjectUtils.isEmpty(taskVo.getCounty())) {
//            whereSql.append(" and (");
//            if (!PlatformObjectUtils.isEmpty(taskVo.getProvince())) {
//                whereSql.append(" task_district like '%" + taskVo.getProvince() + "%'");
//            }
//            if (!PlatformObjectUtils.isEmpty(taskVo.getCity())) {
//                whereSql.append(" or task_district like '%" + taskVo.getCity() + "%'");
//            }
//            if (!PlatformObjectUtils.isEmpty(taskVo.getCounty())) {
//                whereSql.append(" or task_district like '%" + taskVo.getCounty() + "%'");
//            }
//            whereSql.append(") ");
//        }
        if (PlatformObjectUtils.isNotEmpty(taskVo.getProvince())) {
            if (PlatformObjectUtils.isNotEmpty(taskVo.getCity())) {
                String city = "-" + taskVo.getCity();
                if(taskVo.getProvince().equals(taskVo.getCity())){
                    city = "";
                }
                if (PlatformObjectUtils.isNotEmpty(taskVo.getCounty())) {
                    whereSql.append( " and (task.task_district = '" + taskVo.getProvince() + city + "-" + taskVo.getCounty() + "'" +
                            " or task.task_district like '%" + taskVo.getProvince() + city + ",%' or task.task_district like '%," + taskVo.getProvince() + city + "' or task.task_district = '" + taskVo.getProvince() + city +
                            "' or task.task_district like '%" + taskVo.getProvince() + ",%' or task.task_district like '%," + taskVo.getProvince() + "%' or task.task_district = '" + taskVo.getProvince() + "')");
                    countSql.append(" and (task.task_district like '%" + taskVo.getProvince() + city + "-" + taskVo.getCounty()+ "%'" +
                            " or task.task_district like '%" + taskVo.getProvince() + city + "%' or task.task_district = '" + taskVo.getProvince() + city +
                            "' or task.task_district like '%" + taskVo.getProvince() + "%' or task.task_district = '" + taskVo.getProvince() + "')");
                } else {
                    whereSql.append(" and (task.task_district like '%" + taskVo.getProvince() + city + "%' or task.task_district = '" + taskVo.getProvince() + city +
                            "' or task.task_district like '%" + taskVo.getProvince() + "%' or task.task_district = '" + taskVo.getProvince() + "')");
                    countSql.append(" and (task.task_district like '%" + taskVo.getProvince() + city + "、%' or task.task_district = '" + taskVo.getProvince() + city +
                            "' or task.task_district like '%" + taskVo.getProvince() + "%' or task.task_district = '" + taskVo.getProvince() + "')");
                }
            } else {
                whereSql.append(" and (task.task_district like '%" + taskVo.getProvince() + "%' or task.task_district = '" + taskVo.getProvince() + "')");
                countSql.append(" and ( task.task_district like '%" + taskVo.getProvince() + "%' or task.task_district = '" + taskVo.getProvince() + "')");
            }

        }
        String sqlWhole = sql.append(whereSql).append(orderSql).append(limitSql).toString();
        countSql.append(whereSql);
        System.out.println(sqlWhole+"---------"+countSql);
        List<TaskEntity> list = jdbcTemplate.query(sqlWhole, new BeanPropertyRowMapper<>(TaskEntity.class));
        Integer total = jdbcTemplate.queryForObject(countSql.toString(), Integer.class);
        Map<String, Object> map = new HashMap();
        map.put("total", total);
        map.put("rows", list);
        System.out.println("查询时间:" + (System.currentTimeMillis() - start) / 1000);
        return map;
    }

    @Override
    public void update(TaskUpdateVO vo) {
        String sql = "update dzzh_task set task_name = :taskName, disaster_type= :disasterType ,update_user = :updateUser " +
                ",update_time = :updateTime where dt_id = :dtId";
        SqlParameterSource source = new BeanPropertySqlParameterSource(vo);
        namedParameterJdbcTemplate.update(sql, source);
    }

    @Override
    public void deleteAreaDataByTaskId(String id) {
        String sql = "delete from task_district_area where dt_id = '"+id+"'";
        jdbcTemplate.update(sql);
    }

    @Override
    public void deleteTaskDataByTaskId(String id,String userId) {
        String sql = "update dzzh_task set del_flag = '"+YNEnum.Y.toString()+"' ,update_user='"+userId+"',update_time=now() where dt_id = '"+id+"'";
        jdbcTemplate.update(sql);
    }

    @Override
    public TaskEntity viewTask(String dtId) {
        String sql = "select *,st_astext(geom) geom from  dzzh_task where del_flag = '"+YNEnum.N.toString()+"' and  dt_id = '"+dtId+"'";
        List<TaskEntity> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(TaskEntity.class));
        return list==null||list.size()==0?new TaskEntity():list.get(0);
    }

    @Override
    public TaskEntity getTaskWithOutGeom(String dtId) {
        String sql="select dt_id," +
                "task_num," +
                "task_name," +
                "task_region," +
                "task_district," +
                "task_status," +
                "create_user," +
                "create_time," +
                "update_user," +
                "update_time," +
                "del_flag," +
                "disaster_type," +
                "report_id," +
                "create_user_name from dzzh_task where del_flag = '"+YNEnum.N.toString()+"' and  dt_id = '"+dtId+"'";
        List<TaskEntity> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(TaskEntity.class));
        return list==null||list.size()==0?new TaskEntity():list.get(0);
    }

    @Override
    public List<TaskDistrictArea> viewTaskArea(String dtId) {
        String sql = "select * from  task_district_area where  dt_id = '"+dtId+"'";
        List<TaskDistrictArea> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(TaskDistrictArea.class));
        return list==null||list.size()==0?new ArrayList<>():list;
    }

    @Override
    public String getMaxParentNum(String taskYear,String divisionCode) {
        String sql = "select max(task_num) from dzzh_task where  del_flag = '0' and task_num like '%" + taskYear + "%'" +
                "and SUBSTRING (task_num, 5, 2)= '"+divisionCode+"'";
        return jdbcTemplate.queryForObject(sql, String.class);
    }

    @Override
    public Integer findByTaskName(String taskName) {
        String sql = "select count(*) from  dzzh_task where del_flag = '"+YNEnum.N.toString()+"' and  task_name = '"+taskName+"'";
        return jdbcTemplate.queryForObject(sql, Integer.class);
    }

    @Override
    public void updateTaskEvaluateStatus(String taskId,String evaluateItem) {
        String sql = "update dzzh_task set evaluate_item = '"+evaluateItem+"' where dt_id ='"+taskId+"' and del_flag='"+YNEnum.N.toString()+"'";
        jdbcTemplate.update(sql);
    }

    @Override
    public TaskVersion getFinaTaskVersion(String taskId) {
        String sql = "select *  from dzzh_task_version where task_id='"+taskId+"' and result_status='3' and disaster_type='"+ DisasterTypeEnum.SUBSIDENCE.getState() +"'";
        List<TaskVersion> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(TaskVersion.class));
        return list==null||list.size()==0?null:list.get(0);
    }

    @Override
    public TaskEntity getTaskByNum(String taskNum) {
        String sql = "select * from  dzzh_task where del_flag = '"+YNEnum.N.toString()+"' and  task_num = '"+taskNum+"'";
        List<TaskEntity> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(TaskEntity.class));
        return list.size() == 0 ?new TaskEntity():list.get(0);
    }

    @Override
    public void updateReportId(String dtId, String reportId) {
        String sql = "update dzzh_task set report_id = '"+reportId+"' where dt_id ='"+dtId+"'";
        jdbcTemplate.update(sql);
    }

    @Override
    public List<TaskEntity> getAllTask(String userId) {
        StringBuilder sql = new StringBuilder("select *,st_astext(geom) geomText from dzzh_task");
        StringBuilder whereSql = new StringBuilder(" where del_flag = '0' ");
        whereSql.append(" and create_user = '").append(userId).append("'");

        StringBuilder str = new StringBuilder("");
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String role = sysRoleService.getRoleByUserId(userId);
        List<Map> roleMaps = JSONObject.parseArray(role, Map.class);
        for (Map roleMap : roleMaps) {
            str.append(roleMap.get("roleCode")).append(",");
        }
        String roles = str.toString();
        /*if (!roles.contains(FxfzConstants.DZZH_COUN_GL_ROLE) && !roles.contains(FxfzConstants.DZZH_PRI_GL_ROLE)  && !roles.contains(FxfzConstants.DZZH_COUN_YW_ROLE)) {
            whereSql.append(" and create_user = '").append(userId).append("'");
        } else if (roles.contains(FxfzConstants.DZZH_PRI_GL_ROLE)) {
            String areaNameByAreaId = sysAreaService.getAreaNameByAreaId(sUser.getProvinceId());
            if (!PlatformObjectUtils.isEmpty(areaNameByAreaId)) {
                whereSql.append(" and task_district like '%").append(areaNameByAreaId).append("%'");
            }
        }*/
        //国家级可以看所有的
        String sqlWhole = sql.append(whereSql).toString();
        return jdbcTemplate.query(sqlWhole, new BeanPropertyRowMapper<>(TaskEntity.class));
    }

    @Override
    public String getExtent(String taskId) {
        //获取任务范围矩形区域
        String sql = "select ST_extent(geom) from dzzh_task where dt_id='" + taskId + "'";
        return jdbcTemplate.queryForObject(sql, String.class);
    }

    @Override
    public String getCenter(String taskId) {
        //获取任务范围中心点
        String sql = "select ST_AsText(ST_Centroid(ST_extent(geom))) from dzzh_task where dt_id='" + taskId + "'";
        return jdbcTemplate.queryForObject(sql, String.class);
    }
}
